#!/usr/bin/env node

const fs = require('fs'),
      arg1 = process.argv[2],
      arg2 = process.argv[3],
      join = require('path').join,
      log = console.log;

//错误命令
if((process.argv.length === 2 || process.argv.length > 4) || (arg1 !== '-list' && arg1 !== '-show' && arg1 !== '-del')){
  log('请输入正确的命令！');
  process.exit(1);
}
try{
  const sysFile = fs.readdirSync('./sysFile');
//第 1 题
  if(arg1 === '-list'){
    if(arg2 !== undefined){
      log('请输入正确的命令！');
      process.exit(2);          
    }
    let objarr = [],
        i = 0;
    sysFile.map((val)=>{
      let stats = fs.statSync('./sysFile/'+val);
      if(stats.isFile()){
        objarr[i] = {fileName:val, fileSize:stats.size};
        i++;
      }
    });
    objarr.sort((a, b)=>{
      return a.fileSize - b.fileSize;
    });
    //log(JSON.stringify(objarr));
    log('[');
    objarr.map((val, i)=>{
      if(i === objarr.length-1){
        log(`\t{ \"fileName\": \"${val.fileName}\", \"fileSize\": \"${val.fileSize}\" }`);
      }else{
        log(`\t{ \"fileName\": \"${val.fileName}\", \"fileSize\": \"${val.fileSize}\" },`);
      }
    })
    log(']');
    process.exit(3);
  }
//第 2 题
  if(arg1 === '-show'){
    if(arg2 === undefined){
      log('请输入待读取文件名！');
      process.exit(4);
    }
    let notfile = 0;
    sysFile.map((val)=>{
      if(arg2 === val){
        let src = './sysFile/' + val;
        let stats2 = fs.statSync(src);
        if(stats2.isFile()){
          log(fs.readFileSync(src).toString('utf8'));
          process.exit(5);
        }        
      }else{
        notfile++;
      }
    });
    if(notfile === sysFile.length){
      log('文件不存在！');
    }
    process.exit(6);
  }

//第 3 题
  if(arg1 === '-del'){
    if(arg2 === undefined){
      log('请输入待删除文件名！');
      process.exit(7);
    }
    let nofile = 0;
    sysFile.map((val) => {
      if(arg2 === val){
        let src = './sysFile/'+val;
        let stats3 = fs.statSync(src);
        if(stats3.isFile()){
          fs.unlinkSync(src);
          log(val + '删除成功！');        
          process.exit(8);
        }
        if(stats3.isDirectory()){
          delDir(src);
          log(val + '删除成功！');        
          process.exit(9);
        }
      }else{
        nofile++;
      }
    });
    if(nofile === sysFile.length){
      log('文件不存在！');
    }
    process.exit(10);
  }
}catch(e){
  console.error(e.message);
  process.exit(11);
}

function delDir(folder){
  let files = fs.readdirSync(folder);
  for(let i=0; i<files.length; i++){
    let file = join(folder, files[i]);
    if(fs.statSync(file).isFile()){
      fs.unlinkSync(file);
        continue;                
      }
      if(fs.statSync(file).isDirectory()){
        delDir(file);
      }        
    }
  fs.rmdirSync(folder);
}
